package netty;

import java.io.FileNotFoundException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.springframework.utils.LogbackConfigurer;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.Singleton;

public class NettyModule extends AbstractModule {

	@Override
	protected void configure() {
	}

	@Provides
	SocketAddress provideSocketAddress() {
		return new InetSocketAddress(8080);
	}

	@Provides
	@Singleton
	ChannelGroup provideChannelGroup() {
		return new DefaultChannelGroup("http-server");
	}

	@Provides
	ChannelFactory provideChannelFactory() {
		return new NioServerSocketChannelFactory(
				Executors.newCachedThreadPool(),
				Executors.newCachedThreadPool());
	}

	public static void main(String[] args) throws FileNotFoundException {
		LogbackConfigurer.initLogging("config/logback.xml");
		Injector injector = Guice.createInjector(new NettyModule());
		final NettyServer server = injector.getInstance(NettyServer.class);
		server.startAndWait();
		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				server.stopAndWait();
			}
		});
	}
}